package com.mysql.opt;

import java.util.ArrayList;
import java.util.List;

import object.model.MySQL_TableDDL;
import object.model.TableType;
import reflect.engine.DataBaseStructInfoer;
import system.mysql.schema.information.models.VIEWS;

import common.ViewSorter;


public class ViewsOperator extends Operator{
	private List<VIEWS> viewList = null;
	
	public ViewsOperator(){
		this.oprType = "View";
		this.refresh();
	}
	
	@Override
	public List<String[]> getBackupSQLs() {
		// TODO Auto-generated method stub
		List<String[]> SQLs4b = new ArrayList<String[]>();
		List<VIEWS> sortedV = new ViewSorter().getSortedViews(this.viewList);
		for(int i=0;i<sortedV.size();i++){
			VIEWS vI = sortedV.get(i);			
			String[] backUp = {"View: "+vI.getTABLE_NAME(),this.genCreateStatement(vI)};
			SQLs4b.add(backUp);
		}
		return SQLs4b;
	}

	@Override
	public List getObjs() {
		// TODO Auto-generated method stub
		return this.viewList;
	}

	@Override
	public void refresh() {
		// TODO Auto-generated method stub
		DataBaseStructInfoer dbTi = new DataBaseStructInfoer();
		this.viewList = dbTi.getViews();		
	}

	@Override
	public List<String> getNames() {
		// TODO Auto-generated method stub
		List<String> nameLi = new ArrayList<String>();
		for(int i=0;i<this.viewList.size();i++){ 
			nameLi.add(this.viewList.get(i).getTABLE_NAME());
		}
		return nameLi;
	}	
	
	@Override
	public boolean drop(int index) {
		// TODO Auto-generated method stub
		try{
			VIEWS vI = this.viewList.get(index);			
			MySQL_TableDDL tbDDL = new DataBaseStructInfoer().getTableDDL(vI.getTABLE_NAME(), TableType.VIEW);
			String viewName = tbDDL.getTable();
			String dropPhase = tbDDL.getDropStatement();
			this.mysqlQ.toUpdate(dropPhase);
		}catch(Exception e){
			return false;
		}
		return true;
	}

	@Override
	public boolean dropAll() {
		try{
			for(int i=0;i<this.viewList.size();i++){
				VIEWS vI = this.viewList.get(i);
				MySQL_TableDDL tbDDL = new DataBaseStructInfoer().getTableDDL(vI.getTABLE_NAME(), TableType.VIEW);				
				String viewName = tbDDL.getTable();
				String dropPhase = tbDDL.getDropStatement();
				this.mysqlQ.toUpdate(dropPhase);
			}
		}catch(Exception e){
			return false;
		}		
		return true;
	}	
	
	private String genCreateStatement(VIEWS view){
		String stat = "";		
		MySQL_TableDDL tbDDL = new DataBaseStructInfoer().getTableDDL(view.getTABLE_NAME(), TableType.VIEW);
		stat += "/*VIEW : `"+view.getTABLE_SCHEMA()+"`.`"+view.getTABLE_NAME()+"`*/ " + Operator.nextline;
		stat += tbDDL.getDropStatement() + ";" + Operator.nextline;
		stat += tbDDL.getCreateTable() + ";" + Operator.nextline;		
		return stat;
	}
}
